import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Steps, Button, Icon, Tools, Modal,InputItem, Bubble, List, Checkbox } from 'weaver-mobile';
import { Form, RouteLayout } from 'weaver-mobile-page';
import { toJS } from 'mobx';

import { TitleUtil, closest } from '../../util';
import Api from '../../apis/setting';
import SetItemInput from '../widget/SetItemInput';

const { Step } = Steps;
const { Item } = List;
const { getLabel } = Tools;

@inject('mailAccountStore')
@inject('addMailAccountStore')
@withRouter
@observer
export default class AddMailAccount extends Component {

  constructor(props) {
    super(props);
    this.state = {
      newAccount: [],
      autoGetFolderLoading: false,
      chooseFolders: [],
      selectedKeys: '',
      selectDatas: {}
    }
    this.getfolderPath = `${props.location.pathname}/getfolder`
  }

  componentWillMount() {
    const { addMailAccountStore, form, accountId, from } = this.props;
    addMailAccountStore.clear();
    form.resetFields();
    form.setState({ conditioninfo: addMailAccountStore.handleCondition(form.conditioninfo) });
    window.isUmount = false;
    let title = from === 'edit' ? getLabel('510360', '编辑账户') : getLabel('504596', '添加账户');
    TitleUtil.setTitle(title);
    Api.getEmailEditAccountCondition({ id: accountId }).then(res => {
      this.setState({ newAccount: res.conditioninfo })
    });
  }

  componentWillReceiveProps(nextProps) {
    const { from } = this.props;
    let title = from === 'edit' ? getLabel('510360', '编辑账户') : getLabel('504596', '添加账户');
    if (nextProps.path === nextProps.location.pathname) {
      TitleUtil.setTitle(title);
    }
  }

  componentWillUnmount() {
    window.isUmount = true;
    TitleUtil.resetEmElement();
    this.props.mailAccountStore.setState({ sentItemsVal: [] })
  }

  changeStep = (next) => {
    const { addMailAccountStore, form, accountId, mailAccountStore } = this.props;
    const { step, isNewInit } = addMailAccountStore;
    let serverType = form.formParams.serverType;
    let isReceiveSent = form.formParams.isReceiveSent;
    if (next > step) {
      //初始化表单必填项
      form.setState({ conditioninfo: addMailAccountStore.handleCondition(form.conditioninfo, step, serverType, isReceiveSent) });
      const { pass } = form.doValidate();
      if (pass) {
        if (step === 0) {
          // 1 -> 2
          const { conditioninfo } = form;
          const { sendneedSSL, isStartTls } = toJS(form.formParams);
          let newCondition = addMailAccountStore.handleCondition(conditioninfo, next);
          if (Number(sendneedSSL)) {
            newCondition = addMailAccountStore.disabledSwitch(conditioninfo, 'sendneedSSL', Number(sendneedSSL));
          } else if (Number(isStartTls)) {
            newCondition = addMailAccountStore.disabledSwitch(conditioninfo, 'isStartTls', Number(isStartTls));
          }
          form.setState({ conditioninfo: newCondition });
          addMailAccountStore.setState({ step: next });
          if (!accountId && isNewInit) {
            // 新增时获取默认数据
            Api.getMailAccountDefaultInfo({
              accountMailAddress: form.formParams.accountMailAddress,
            }).then(res => {
              const { emailAccountBean, status } = res;
              if (Number(status)) {
                addMailAccountStore.setState({ bean: emailAccountBean });
                addMailAccountStore.updateFormFields(emailAccountBean, form);
                if (emailAccountBean.sentItems) { // sentItems修改数据格式，单独处理
                  let sentItemsVal = []
                  emailAccountBean.sentItems.split(',').forEach((item, index) => {
                    sentItemsVal = [...sentItemsVal, {id: String(index), name: item, validate: true}]
                  })
                  mailAccountStore.setState({ sentItemsVal })
                } 
              }
            });
          }
        } else if (step === 1) {
          // 2 -> 3
          addMailAccountStore.setState({ step: next, loading: true });
          let params = {
            ...form.formParams,
            operation: accountId ? 'update' : 'add',
          };
          if (String(isReceiveSent) !== '1' || String(serverType) !== '2') {
            params = {...params, sentItems: ''}
          }
          if (serverType === '1') {
            params = {...params, isReceiveSent: '0'}
          }
          if (accountId) { params = { ...params, id: accountId }; }
          Api.makeUserMailAccount(params).then(res => {
            const { status, mailState, json } = res;
            if (!res.flag && (res.errorType && res.errorType == 'port')) {
              addMailAccountStore.setState({ step: next-1 , loading: false});
              Modal.alert(res.msg);
              return;
            }
            if (Number(status)) {
              addMailAccountStore.setState({ loading: false, mailState, results: json });
            }
          });
        }
      }
    } else if (next < step) {
      if (step === 1) {
        // 2 -> 1
        form.setState({ conditioninfo: addMailAccountStore.handleCondition(form.conditioninfo, next) });
      }
      addMailAccountStore.setState({ step: next, isNewInit: false });
    }

  }

  confirm = () => {
    const { history, form, addMailAccountStore, mailAccountStore } = this.props;
    form.resetFields();
    addMailAccountStore.clear();
    mailAccountStore.tableListStore.refreshTableList();
    history.go(-1);
  }

  onChange = (c, v) => {
    const { form, addMailAccountStore, addMailAccountStore: { bean } } = this.props;
    const domkey = c.domkey.join('__');
    if (domkey === 'serverType') {
      const value = { ...bean, popServer: '', serverType: v, popServerPort: v === '1' ? 110 : 143 };
      addMailAccountStore.updateFormFields(value, form);
    } else if (domkey === 'sendneedSSL' || domkey === 'isStartTls') {
      form.setState({ conditioninfo: addMailAccountStore.disabledSwitch(form.conditioninfo, domkey, v) });
      //this.setState({ newAccount: [addMailAccountStore.disabledSwitch(form.conditioninfo, domkey, v)[1]] })
      form.onChange(c, v);
    } else if (domkey === 'openIdentifyInvoice') {
      if(1 === v){
        addMailAccountStore.setState({ invoiceVisible: true })
      }
      form.onChange(c, v);
    }else {
      form.onChange(c, v);
    }
  }

  onAutoGetFolderName = () => {
    const { form, history, addMailAccountStore } = this.props;
    const { formParams: { popServer, accountMailAddress, accountPassword } } = form;
    if (!popServer) {
      Bubble.error(getLabel('522601','请填写 接收邮件服务器 信息'), 1, { top: '10%' });
    } else {
      let params = {
        mailuserAddress: accountMailAddress,
        mailuserPassword: accountPassword,
        imapServer: popServer
      }
      this.setState({ autoGetFolderLoading: true }, async() => {
        let res = await addMailAccountStore.onGetFolderName(params)
        if (res.getFolderStatus === '1') {
          let chooseFolders = res.sentItemNames.map((item, index) => {
            return ({ key: index, showname: item.folderName, selected: false, isRec: item.isRec || false })
          });
          this.setState({ chooseFolders, selectedKeys: '', selectDatas: {} })
          history.push({pathname: this.getfolderPath})
        } else {
          Bubble.error(getLabel(522602, '获取失败，请重试！'), 1, { top: '10%' });
        }
        this.setState({ autoGetFolderLoading: false })
      })
    }
  }

  getFields = (condition) => {
    const { form, mailAccountStore } = this.props;
    const { formParams: { needSave, serverType, isReceiveSent, sentItems } } = form;
    const fields = [];
    if (condition && condition.items) { condition = condition.items; }
    if (Array.isArray(toJS(condition))) {
      condition.forEach((field) => {
        let extra = field.domkey[0] === 'needSave' && needSave * 1 !== 1 ? <span className={`${field.domkey}-tip`}>{getLabel(510163, '关闭后将删除邮箱服务器上的对应邮件，请谨慎设置！')}</span> : null;
        if ((field.domkey[0] === 'ews_service_url' || field.domkey[0] === 'ews_domain' || field.domkey[0] === 'ews_version') && ("1" === serverType || "2" === serverType)) {
          return;
        } else if ((field.domkey[0] === 'popServer' || field.domkey[0] === 'popServerPort' || field.domkey[0] === 'smtpServer' || field.domkey[0] === 'smtpServerPort' || field.domkey[0] === 'getneedSSL'
          || field.domkey[0] === 'sendneedSSL' || field.domkey[0] === 'isStartTls' || field.domkey[0] === 'needCheck' || field.domkey[0] === 'needSave') && "3" === serverType) {
          return;
        } else if (field.domkey[0] === 'isReceiveSent' && serverType === '1') {
          return;
        } else if (field.domkey[0] === 'sentItems' && !(serverType === '2' && Number(isReceiveSent))) {
          return;
        } else if (field.domkey[0] === 'sentLastTime' && !Number(isReceiveSent)) {
          return;
        }

        if (field.domkey[0] === 'sentItems') {
          const renderSentItems = (
            <SetItemInput
              value={toJS(mailAccountStore.sentItemsVal)}
              extra={(
                <div className={'add-mail-account-autogetfolder'} onClick={this.onAutoGetFolderName}>{getLabel('522841','点击自动获取')}</div>
              )}
              onChange={(v) => {
                mailAccountStore.setState({ sentItemsVal: v || [] })
                this.onChange(field, v[0] && v[0].name || '')
              }}
            />
          )
          field.conditionType = 'CUSTOM'
          let fieldProps = {
            key: field.domkey.join('__'),
            form: form,
            fieldConfig: field,
            children: renderSentItems
          }
          fields.push(<Form.Item {...fieldProps}/>)
        } else {
          fields.push(<Form.Item
            key={field.domkey.join('__')}
            form={form}
            fieldConfig={field}
            onChange={this.onChange}
            extra={extra}
          />);
           if(field.domkey[0] === 'openIdentifyInvoice'){
            fields.push(<InputItem
              value={getLabel('515637', '仅识别邮件中的增值税电子发票')}
              disabled
            />)
          }
        }
      });
    }
    return fields;
  }

  getResultItem = (item, err) => {
    const { addMailAccountStore } = this.props;
    const { loading } = addMailAccountStore;
    let errCom;
    if (!loading && err) {
      const { ischeck, errormess } = err;
      errCom = !ischeck && (
        <div className="add-mail-account-result-item-err">
          <span className="add-mail-account-result-item-msg">{errormess && errormess.errorHint}</span>
          <a onClick={() => addMailAccountStore.setState({ visible: true, errorHint: errormess && errormess.errorString })}>{getLabel('17480', '查看日志')}</a>
        </div>
      );
    }
    return (
      <li className={`add-mail-account-result-item ${(loading || !err) ? '' : (err.ischeck ? 'success' : 'failed')}`}>
        {(loading || !err) ? <Icon type="loading" /> : (err.ischeck ? <Icon type="check-circle" /> : <Icon type="cross-circle-o" />)}
        <div className="add-mail-account-result-item-content">
          {item}
          {errCom}
        </div>
      </li>
    );
  }

  renderContent = () => {
    const { addMailAccountStore, form, form: { conditioninfo }, from } = this.props;
    const { step, results, mailState, visible, errorHint, loading } = addMailAccountStore;
    let field;
    let type = '';
    let text = '';
    switch (step) {
      case 2:
        // 结果
        const { smtpState, smtpLoginState, popState, popLoginState, exchangeSendState, exchangeLoginState } = results;
        const { formParams: { serverType } } = form;
        text = mailState ? getLabel('384432', '邮件账户检测通过！') : getLabel('82862', '邮件账户检测不通过！请检查设置！');
        type = mailState ? 'mail-send-success' : 'mail-error';
        field = (
          <ul className="add-mail-account-result">
            {("1" === serverType || "2" === serverType) && this.getResultItem(`${getLabel('82877', '查找发送邮件服务器')}(SMTP)`, smtpState)}
            {this.getResultItem(serverType === '3' ?`${getLabel('82878', '登录到发送邮件服务器')}`:`${getLabel('82878', '登录到发送邮件服务器')}`+"(SMTP)", serverType === '3' ? exchangeSendState : smtpLoginState)}
            {this.getResultItem(`${getLabel('82883', '发送测试邮件')}`, serverType === '3' ? exchangeSendState : smtpLoginState || popLoginState)}
            {("1" === serverType || "2" === serverType) && this.getResultItem(`${getLabel('82881', '查找接收邮件服务器')}(${serverType === '2' ? 'IMAP' : 'POP3'})`, popState)}
            {this.getResultItem(`${getLabel('82882', '登录到接收邮件服务器')}${serverType === '3' ? "" : serverType === '2' ? '(IMAP)' : '(POP3)'}`, serverType === '3' ? exchangeLoginState : popLoginState)}
            <Modal
              transparent
              visible={visible}
              maskClosable={false}
              onClose={() => addMailAccountStore.setState({ visible: false })}
              title={getLabel('17480', '查看日志')}
              footer={[{
                text: getLabel('826', '确定'),
                onPress: () => addMailAccountStore.setState({ visible: false })
              }]}
              wrapProps={{
                onTouchStart: (e) => {
                  // fix touch to scroll background page on iOS
                  if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
                    return;
                  }
                  const pNode = closest(e.target, '.am-modal-content');
                  if (!pNode) {
                    e.preventDefault();
                  }
                }
              }}
            >
              {errorHint}
            </Modal>
          </ul>
        );
        break;
      default:
        // 表单
        const edit_group = toJS(conditioninfo)[step];
        const account_group = step === 1 ? toJS(this.state.newAccount)[0] : toJS(conditioninfo)[0];

        const group = from === 'edit' ? edit_group : account_group;
        field = this.getFields(group);
        text = group && group.title;
        type = step === 1 ? 'mail-server' : 'mail-basic-information';
        break;
    }
    return (
      <div className="add-mail-account-content">
        <div className={`add-mail-account-header ${step === 2 ? `result ${loading ? 'waitting' : ''}` : ''}`}>
          {type && <Icon className="add-mail-account-icon" type={type} />}
          <div className="add-mail-account-text">{text}</div>
        </div>
        {field}
      </div>
    );
  }

  renderFolderList = (list) => (
    <div className={`add-mail-account-getfolder-list-body`}>
      {list.length > 0 && list.map(d => {
        return (
          <Item key={d.key}>
            <div className={`add-mail-account-getfolder-list-item`}>
              <div className={`add-mail-account-getfolder-list-item-label`} style={d.isRec ? { color: 'red' } : {}}>
                {d.showname}
              </div>
              <div className={`add-mail-account-getfolder-list-item-checkbox`}>
                <Checkbox
                  checked={this.state.selectedKeys === d.key}
                  onChange={e => this.onSelectedKeys(d, e.target.checked)}
                />
              </div>
            </div>
          </Item>
        )
      })}
    </div>
  )

  onSelectedKeys = (d, v) => {
    if (v) {
      this.setState({selectedKeys: d.key, selectDatas: d})
    }
  }

  onSetFolderName = () => {
    const { selectDatas } = this.state
    const { form, history, mailAccountStore } = this.props;
    if (selectDatas.showname) {
      form.updateFields({ sentItems: { value: selectDatas.showname } });
      let sentItemsVal = [{id: selectDatas.key, name: selectDatas.showname, validate: true}]
      mailAccountStore.setState({ sentItemsVal: sentItemsVal })
      this.setState({
        chooseFolders: [],
        selectedKeys: '',
        selectDatas: {}
      })
      history.go(-1);
    } else {
      Bubble.error(getLabel('522597','您还未选择文件夹！'), 1, { top: '10%' })
    }
  }

  render() {
    const { addMailAccountStore, addMailAccountStore: { step, loading, mailState,invoiceVisible } } = this.props;
    const steps = [1, 2, 3].map(i => <Step key={`step${i}`} icon={(i - 1) > step ? i : undefined} />);
    return (
      <RouteLayout>
        <div key="addMailAccount" className="add-mail-account wm-route-layout route-layout-form">
          <Steps current={step} direction="horizontal">{steps}</Steps>
          {this.renderContent()}
          {!loading && <div className="btn-group">
            <Button
              key="pre"
              onClick={() => this.changeStep(step - 1)}
              className={(step === 0 || (step === 2 && mailState)) ? 'hidden' : ''}
              disabled={this.state.autoGetFolderLoading}
            >
              {getLabel('1876', '上一步')}
            </Button>
            <Button
              key="next"
              onClick={() => step === 2 ? this.confirm() : this.changeStep(step + 1)}
              type="primary"
              disabled={this.state.autoGetFolderLoading}
            >
              {step === 2 ? getLabel('309', '关闭') : getLabel('1402', '下一步')}
            </Button>
            
            <Modal
              transparent
              visible={invoiceVisible}
              maskClosable={false}
              onClose={() => addMailAccountStore.setState({ invoiceVisible: false })}
              title={<span style={{'fontWeight':'900','fontSize':'18px'}} >{getLabel(510826, '温馨提示')}</span>}
              footer={[{
                text: getLabel('826', '确定'),
                onPress: () => addMailAccountStore.setState({ invoiceVisible: false })
              }]}
              wrapProps={{
                onTouchStart: (e) => {
                  // fix touch to scroll background page on iOS
                  if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
                    return;
                  }
                  const pNode = closest(e.target, '.am-modal-content');
                  if (!pNode) {
                    e.preventDefault();
                  }
                }
              }}
            >
            <div style={{ height: 100, overflow: 'scroll' }}>
              <p style={{'fontWeight':'700'}}>{getLabel(515692, '亲爱的用户，欢迎使用发票识别功能。')}</p>
              <p>{getLabel(515695, '1.为保证发票识别功能正常使用，我们会根据需要收集个人邮箱中公司指定发件人发送的发票信息，获取之后也仅作为用户及其公司在OA系统中的相关财务业务往来')}</p>
              <p>{getLabel(515696, '2.我们非常重视您的隐私和个人信息保护，未经授权，不会私自收集、使用、共享您邮件中的个人信息，请放心使用')}</p>
            </div>
            </Modal>

          </div>}
          <Route
            key="getfolder"
            path={this.getfolderPath}
            render={() => {
              const button = [
                {
                  key: 'submit',
                  text: getLabel('826', '确定'),
                  onClick: this.onSetFolderName,
                  type: 'primary',
                }
              ]
              return (
                <RouteLayout>
                  <div className="wm-route-layout add-mail-account-getfolder">
                    <List className='add-mail-account-getfolder-list'>
                      <div className='add-mail-account-getfolder-tip'>
                        <span style={{ color: 'red' }}>
                          {getLabel('525627', '标红名称为推荐文件夹')}
                        </span>
                      </div>
                      {this.renderFolderList(this.state.chooseFolders)}
                    </List>
                    <RouteLayout.ButtonGroup
                      data={button}
                    />
                  </div>
                </RouteLayout>
              );
            }}
          />
        </div>
      </RouteLayout>
    );
  }
}
